/**
  ******************************************************************************
  * @file           : XYXKC_openAi.cpp
  * @author         : admin
  * @brief          : None
  * @attention      : None
  * @date           : 2025/2/28
  ******************************************************************************
  */

#include "XYXKC_openAi.h"

void XYXKC_openAi::openAiBegin(String url, String apiKey, String model){
    _url = url;
    _apiKey = apiKey;
    _model = model;
};
void XYXKC_openAi::setRole(String system){
    _system = system;
};
String XYXKC_openAi::getGPTAnswer(String inputText){
    HTTPClient http;
    http.setTimeout(20000);
    http.begin(_url);
    http.addHeader("Content-Type", "application/json");
    String token_key = String("Bearer ") + _apiKey;
    http.addHeader("Authorization", token_key);
    String payload = "{\"model\":\""+_model+"\",\"messages\":[{\"role\":\"system\",\"content\":\""+_system+"\"},{\"role\":\"user\",\"content\":\"" + inputText + "\"}]}";
    int httpResponseCode = http.POST(payload);
    if (httpResponseCode > 0) {
        String response = http.getString();
        http.end();
        if(httpResponseCode == 200){
            DynamicJsonBuffer jsonBuffer;
            JsonObject& object = jsonBuffer.parseObject(response);
            String outputText = object["choices"][0]["message"]["content"];
            return outputText;
        }
    }
    http.end();
    return "<error>";
};